/*
Copyright 2020 @BuildRun.io.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controllers

import (
	"buildrun.io/runner-helper/pkg/runner"
	"context"
	"github.com/vinkdong/gox/log"
	"k8s.io/apimachinery/pkg/api/errors"

	"github.com/go-logr/logr"
	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"

	runnerv1 "buildrun.io/runner-helper/api/v1"
)

// SharedConfigurationReconciler reconciles a SharedConfiguration object
type SharedConfigurationReconciler struct {
	client.Client
	Log           logr.Logger
	Scheme        *runtime.Scheme
	RunnerManager *runner.Manager
}

// +kubebuilder:rbac:groups=runner.buildrun.io,resources=sharedconfigurations,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=runner.buildrun.io,resources=sharedconfigurations/status,verbs=get;update;patch

func (r *SharedConfigurationReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
	_ = context.Background()
	_ = r.Log.WithValues("sharedconfiguration", req.NamespacedName)

	// your logic here
	instance := &runnerv1.SharedConfiguration{}
	//这一步将C7NHelmRelease中的值 注入到这个instance 俗话就是得到C7NHelmRelease实例
	err := r.Client.Get(context.TODO(), req.NamespacedName, instance)
	if err != nil {
		if errors.IsNotFound(err) {
			// 判断是否存在 不存在表示被删除操作
			log.Errorf("%s被删除了", req.Name)
			r.RunnerManager.RemoveRunner(req.Name)
			return ctrl.Result{}, nil
		}
		// Error reading the object - requeue the request.
		return ctrl.Result{}, err
	}

	if err := r.RunnerManager.AddRunner(instance); err != nil {
		return ctrl.Result{}, err
	}

	return ctrl.Result{}, nil
}

func (r *SharedConfigurationReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&runnerv1.SharedConfiguration{}).
		Complete(r)
}
